package com.wnxy.email.listener;

import cn.hutool.core.util.RandomUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Map;

@Component
public class EmailListener {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 监听器业务实现
     */
    @RabbitListener(queues = "q-mail")
    public void sendEmail(Map<String,String> map) {
        System.out.println("map = " + map);
        // 创建邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置发件人
        message.setFrom(map.get("from"));
        // 设置收件人
        message.setTo(map.get("to"));
        // 设置邮件内容: 四位随机数
        message.setText(map.get("code"));
        // 设置邮件标题
        message.setSubject(map.get("subject"));
        // 发邮件
        javaMailSender.send(message);
        // 验证码存储到redis，有效时间5分钟
        stringRedisTemplate.opsForValue().set(map.get("to"),map.get("code"), Duration.ofMinutes(5));
    }
}
















